


import axios from 'axios'
import router from '../router'
import store from '../store'
import { actionsTypes } from '../store'
import { MessageBox, Message } from 'element-ui'
const { VUE_APP_API_URL } = process.env

var instance = axios.create({
  // baseURL: window.location.origin + VUE_APP_API_URL,
  baseURL: VUE_APP_API_URL, // 请求URL公共部分
  withCrendentials: true
})

instance.interceptors.request.use(function (config) {
  config.headers.common['Accept-Language'] = localStorage.getItem('kycloud_lang') || 'en'
  // 获取token
  const token = localStorage.getItem('BCM-T')
  config.headers.common['Authorization'] = `Bearer ${token}`

  return config
})
instance.interceptors.response.use(
  response => {
    if (response.headers['content-disposition']) {
      return response
    } else {
      const { code, msg } = response.data
      if (code !== 100000 && code !== 200) {
        Message({ message: msg, type: 'error' })
      }
      return Promise.resolve(response.data);
      // return response.data
    }
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          store.commit(actionsTypes.HIDE_ALL_MODALS)
          store.commit(actionsTypes.CLEAR_USER_INFO)

          MessageBox.alert('登录状态已过期，请重新登录', '系统提示', {
            confirmButtonText: '确定',
            type: 'warning',
            callback: action => {
              console.log(action);
            }
          })
        // router.push({ name: 'login' })
      }
    }
    const result = error.response.data
    // const message = result && result.msg || 'Unknow Error'
    const message = result || 'Unknow Error'
    window.NotebookVue.$message.error(message)
    return Promise.reject(error.response)
  }
)

export default instance
